<template>
  <el-form ref="form" :model="form" label-width="100px">
    <el-form-item label="规则名称" prop="ruleName">
      <el-input v-model="form.ruleName" :disabled="detailDisabled"></el-input>
    </el-form-item>
    <el-form-item label="通道类型" prop="tradeType">
      <el-select v-model="form.tradeType" :disabled="detailDisabled">
        <el-option :label="tradeTypeItems[form.tradeType]" :value="form.tradeType"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="执行顺序" prop="sequence">
      <el-input v-model="form.sequence" :disabled="detailDisabled"></el-input>
    </el-form-item>
    <el-form-item label="规则类型" prop="ruleType">
      <el-select v-model="form.ruleType" @change="aaFn(form.ruleType, form)" :disabled="(detailDisabled == true || editDisabled == true) ? true : false">
        <el-option :label="item" :value="index" v-for="(item, index, key) in getRuleType" :key="key"></el-option>
      </el-select>
    </el-form-item>

    <!--*********************************************************规则配置************************************************************************-->
    <fieldset>
      <legend>规则配置</legend>
    </fieldset>
    <el-button v-show="detailDisabled === false" v-if="form.ruleType == 0" type="primary" class="margin-left-30" size="small" @click="addRuleFn"><i class="el-icon-plus"></i></el-button>
    <el-form-item label="路由规则">
      <!--**************************************************通道类型：指定通道**********************************************************************-->
      <el-row v-if="form.ruleType == 0">
        <el-col :span="20" class="padding-right">
          <el-row v-for="(item, index, key) in form.conditions" :key="key">
            <el-col :span="8">
              <el-form-item class="text-align-left">
                <el-select :value="item.conditionKey" placeholder="" :disabled="detailDisabled" @input="changeConditionFn($event, item.conditionKey, item)">
                  <el-option :label="v.conditionName" :value="v.conditionKey" v-for="(v, key) in conditionTemplet" :key="key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item class="text-align-left">
                <el-select :value="item.operator" @input="changeOperatorFn($event, item.operator, item)" placeholder="" :disabled="detailDisabled">
                  <el-option :label="v" :value="v" v-for="(v, key) in item.operatorList" :key="key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!--<el-col :span="5" v-for="(v, i) in item.params" v-if="item.operator !== 'in'">
              <el-col :span="10" v-if="item.operator !== 'eq' || (item.operator === 'eq' && i == 0) || item.operator !== 'in'">
                <el-form-item class="text-align-left ">&nbsp;&nbsp;&nbsp;{{az(i)}}=</el-form-item>
              </el-col>
              <el-col :span="14" v-if="item.operator !== 'eq' || (item.operator === 'eq' && i == 0) || item.operator !== 'in'">
                <el-form-item class="text-align-left">
                  <el-input size="small" v-model="item.params[i]" placeholder="请输入内容"></el-input>
                </el-form-item>
              </el-col>
            </el-col>-->
            <el-col :span="1" v-if="item.operator != '' && item.operator !== 'in' && item.operator != undefined">
              <el-form-item class="text-align-left ">a=</el-form-item>
            </el-col>
            <el-col :span="4" v-if="item.operator != '' && item.operator !== 'in' && item.operator != undefined">
              <!-- ************************************************************************************************************************************** -->
              <el-form-item class="text-align-left" v-if="Object.keys(objList).indexOf(item.conditionKey) != -1">
                <el-select v-model="item.params[0]" :disabled="detailDisabled">
                    <template v-for="(d, key) in objList[item.conditionKey]">
                      <el-option  :key="key" v-if="typeof(d) !='string'"  :label="d | a(item.conditionKey)" :value="d | a(item.conditionKey,'value')">
                    </el-option>
                    <el-option  :key="key" v-if="typeof(d) =='string'" :label="d" :value="key">
                    </el-option>
                  </template>
                </el-select>
              </el-form-item>
              <el-form-item class="text-align-left" v-else>
                <el-input size="small" v-model="item.params[0]" placeholder="请输入内容" :disabled="detailDisabled"></el-input>
              </el-form-item>
              <!-- ************************************************************************************************************************************** -->
            </el-col>
            <el-col :span="1" v-if="item.operator != 'eq' && item.operator != '' && item.operator != 'in' && item.operator != undefined">
              <el-form-item class="text-align-left ">b=</el-form-item>
            </el-col>
            <el-col :span="4" v-if="item.operator != 'eq' && item.operator != '' && item.operator != 'in' && item.operator != undefined">
              <el-form-item class="text-align-left">
                <el-input size="small" v-model="item.params[1]" placeholder="请输入内容" :disabled="detailDisabled"></el-input>
              </el-form-item>
            </el-col>
            <!-- ############################################################################################################################################# -->
            <el-col :span="10" v-if="item.operator === 'in' && Object.keys(objList).indexOf(item.conditionKey) != -1">
              <el-select v-model="item.params" multiple  :disabled="detailDisabled">
                 <template v-for="(d, key) in objList[item.conditionKey]">
                      <el-option  :key="key" v-if="typeof(d) !='string'"  :label="d | a(item.conditionKey)" :value="d | a(item.conditionKey,'value')">
                    </el-option>
                    <el-option  :key="key" v-if="typeof(d) =='string'" :label="d" :value="key">
                    </el-option>
                  </template>
              </el-select>
            </el-col>
            <!-- ###################################################################################################################################### -->
            <el-col :span="1" v-show="detailDisabled === false">
              <el-form-item class="text-align-left">
                <el-button size="small" @click="subRuleFn(index)">
                  <i class="el-icon-minus"></i>
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <!--***************************************************通道类型：指定通道**********************************************************************-->
      <!--**********************************************通道类型：普通通道**********************************************************************-->
      <div v-if="form.ruleType != 0">
        <el-select :value="form.conditions[0].conditionKey" :disabled="detailDisabled" @input="changeConditionFn($event, form.conditions[0].conditionKey, form.conditions[0])">
          <el-option :label="v.conditionName" :value="v.conditionKey" v-for="(v, key) in conditionTemplet" :key="key"></el-option>
        </el-select>
      </div>
      <!--**********************************************通道类型：普通通道结束**********************************************************************-->
    </el-form-item>
    <fieldset v-if="form.ruleType == 0">
      <legend>指定通道</legend>
    </fieldset>
    <el-form-item v-if="form.ruleType == 0" label="指定通道" prop="channelCode">
      <el-select v-model="form.channelCode" :disabled="detailDisabled">
        <el-option :label="v" :value="i" v-for="(v, i, key) in channelCodeList" :key="key"></el-option>
      </el-select>
    </el-form-item>
    <!--*********************************************************规则配置结束************************************************************************-->

    <fieldset class="margin-bottom-10"></fieldset>
    <el-form-item label="备注" prop="remark">
      <el-input :disabled="detailDisabled" type="textarea" v-model="form.remark"></el-input>
    </el-form-item>

    <el-form-item v-show="detailDisabled === false">
      <el-button type="primary" @click="onSubmit('form')">确定</el-button>
      <el-button @click="onCanel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
  import {
    getChannelCondition,
    getOperatorList,
    getConditionTemplet,
    bankList,
    getRuleDetail,
    updateRuleInfo,
    getProduct,
    queryChannel,
    queryChannelCode,
    getRepayType,
    getCommissionOrgCode,
    getLenderOrgCode,
    getEntranceOrgCode,
    getWithholdType
  } from '@/services/getData'
  import { OutputLowercase } from '@/common/mUtils'
  export default {
    name: 'add-edit-route-rules',
    data() {
      return {
        channelCodeList: {},
        ruleItems: [],
        defaultConditions: {
          "ruleKey": "",
          "conditionKey": "",
          "conditionName": "",
          "conditionId": '',
          "operator": "",
          "additionalKey": "",
          "additionalValue": "",
          "params": [],
          "operatorList": {}
        },
        getRuleType: [],
        conditionTemplet: [],
        operatorList: {},
        operatorObj: {},
        form: {
          "ruleId": null,
          "tradeType": '1',
          "ruleType": '0',
          "ruleKey": "",
          "ruleName": "",
          "status": '',
          "sequence": null,
          "channelCode": "",
          "remark": "",
          "conditions": [{
            "ruleKey": "",
            "conditionKey": "",
            "conditionName": "",
            "conditionId": null,
            "operator": "",
            "params": [],
            "operatorList": {}
          }]
        },
        allBankList: {},
        defaultForm: {
          "ruleId": null,
          "tradeType": '1',
          "ruleType": '0',
          "ruleKey": "",
          "ruleName": "",
          "status": '',
          "sequence": null,
          "channelCode": "",
          "remark": "",
          "conditions": [{
            "ruleKey": "",
            "conditionKey": "",
            "conditionName": "",
            "conditionId": null,
            "operator": "",
            "additionalKey": "",
            "additionalValue": "",
            "params": [],
            "operatorList": {}
          }]
        },
        defaultRuleType:'',
        detailDisabled: false,
        repayTypeList: {},
        commissionOrgCodeList: {},
        lenderOrgCodeList: {},
        entranceOrgCodeList: {},
        withholdTypeList: {},
        productList: [],
        allBankList: [],
        objList:{
          'BANK_CODE': [],
          'PRODUCT_NO': [],
          'REPAY_TYPE': [],
          'COMMISSION_ORG_CODE': [],
          'LENDER_ORG_CODE': [],
          'WITHHOLD_TYPE': [],
          'ENTRANCE_ORG_CODE': []
        },
        editDisabled: false
      }
    },
    props: {
      ruleId: {
        type: Number,
        default: 0
      },
      ruleType: {
        type: String,
        default: '0'
      },
      rmd: {
        type: Number,
        default: 0
      },
      buttonType: ''
    },
    watch: {
      rmd: function() {
        this.supportedBankList()
        this.getProductFn()
        this.queryChannelCodeFn()
        this.detailDisabled = false
        this.editDisabled = false
        let defaultForm = JSON.parse(JSON.stringify(this.defaultForm))
        this.form = Object.assign({}, defaultForm)
        if (this.buttonType == "新增") {
          this.initConditionTemplet(0)
        } else if (this.buttonType == "编辑") {
          this.initConditionTemplet(1)
          this.getRuleDetailFn()
          this.editDisabled = true
        } else if (this.buttonType == "详情") {
          this.initConditionTemplet(1)
          this.getRuleDetailFn()
          this.detailDisabled = true
        }
      }
    },
    filters: {
      a: function (item,conditionKey,type){
        let value = ''
        switch (conditionKey){
          case 'BANK_CODE':
            if(type == 'value'){
              value = item.bankCode
            }else{
              value = item.bankName
            }
          break;
        }
        return value
      }
    },
    created() {
      this.tradeTypeItems = this.GLOBAL.getChanelType()
      this.getAuthenticationType = this.GLOBAL.getAuthenticationType()
      this.getRuleType = this.GLOBAL.getRuleType()
      this.getEntranceOrgCodeFn()
      this.getRepayTypeFn()
      this.getCommissionOrgCodeFn()
      this.getLenderOrgCodeFn()
      this.getWithholdTypeFn()
      this.supportedBankList()
      this.getProductFn()
      this.queryChannelCodeFn()
      if(this.buttonType == "新增") {
        this.initConditionTemplet(0)
      } else if (this.buttonType == "编辑") {
        this.initConditionTemplet(1)
        this.getRuleDetailFn()
        this.editDisabled = true
      } else if (this.buttonType == "详情") {
        this.initConditionTemplet(1)
        this.getRuleDetailFn()
        this.detailDisabled = true
      }

    },
    methods: {

      // 添加规则
      addRuleFn() {
        let defaultConditions = JSON.parse(JSON.stringify(this.defaultConditions))
        this.form.conditions.push(Object.assign({}, defaultConditions))
      },

      // 删除当前通道限制条件
      subRuleFn(i) {
        if (i === 0) {
          this.$message({
            type: 'error',
            message: '指定规则必须要有规则'
          });
          return false
        }
        this.form.conditions.splice(i, 1)
      },
      onSubmit(form) {
        let flag = true
        let tip = ''
        if (this.form.ruleName === '') {
          tip = '请输入规则名称'
          flag = false
        } else if ( this.form.sequence === null || this.form.sequence === '') {
          tip = '请输入执行顺序'
          flag = false
        } else if (this.form.remark === '') {
          tip = '请填写备注'
          flag = false
        }
        if (flag === false) {
          this.$message({
            type: 'error',
            message: tip
          });
          return false
        }
        let params = {}
        params['operatorName'] = sessionStorage.getItem('ms_username')
        params['operatedMenu'] = "代收通道路由管理"
        if(this.buttonType == "新增") {
          params['operatedButton'] = "新增规则按钮"
        } else if (this.buttonType == "编辑") {
          params['operatedButton'] = "编辑规则按钮"
        }
        params['tradeType'] = this.form.tradeType
        params['ruleType'] = this.form.ruleType
        params['ruleKey'] = this.form.ruleKey
        params['ruleName'] = this.form.ruleName
        params['channelCode'] = this.form.channelCode
        params['sequence'] = this.form.sequence
        params['remark'] = this.form.remark
        params['conditions'] = []
        if(params['ruleType'] == 0) {
          params['conditions'] = this.form.conditions
        } else {
          let conditionList = {}
          conditionList.conditionId = this.form.conditions[0].conditionId
          conditionList.conditionKey = this.form.conditions[0].conditionKey
          conditionList.conditionName = this.form.conditions[0].conditionName
          conditionList.ruleKey = this.form.conditions[0].ruleKey
          params['conditions'].push(conditionList)
        }
        updateRuleInfo(params).then(
          res => {
            if(res.resultCode == 1) {
              this.$message({
                type: 'success',
                message: "提交成功"
              });
              this.$emit("chanelClose")
            } else {
              this.$message({
                type: 'error',
                message: res.errorDesc
              });
            }
          }
        )
      },
      onCanel() {
        this.$emit("chanelClose", "cancel")
      },

      aaFn(v, form){
        if(v == 1) {
          this.initConditionTemplet(1)
        } else {
          this.initConditionTemplet(0)
        }
        if (this.buttonType == "新增") {
          let defaultConditions = JSON.parse(JSON.stringify(this.defaultConditions))
          this.form.conditions = []
          this.form.conditions.unshift(Object.assign({}, defaultConditions))
        }
      },

      // 修改操作符
      changeOperatorFn(e, opt, v) {
        v.params = []
        v.operator  = e
        if(v == 'eq') {

        } else if(v == 'in') {
//        if( k == 'PRODUCT_NO'){
//          this.inList = arr
//        } else if( k == 'BANK_CODE'){
//          this.inList = this.allBankList
//        }
        } else {
          // this.form.conditions[i].params = []
        }
      },

      // 查询规则详情
      getRuleDetailFn() {
        let params = {}
        params["ruleId"] = this.ruleId
        params["operatorName"] = sessionStorage.getItem('ms_username')
        params["operatedMenu"] = "通道路由规则管理"
        params["operatedButton"] = this.buttonType

        try {
          getRuleDetail(params).then((res) => {
            if(res.resultCode == 1) {
              res.rows[0].ruleType = res.rows[0].ruleType.toString()
              this.form = res.rows[0]
              this.initConditionTemplet(this.form.ruleType)
              this.defaultRuleType = this.form.ruleType
  //          this.defaultConditions = this.form.conditions
            } else {
              throw new Error(res.message)
            }
          })

        } catch(err) {
          console.log('获取数据失败', err)
        }
      },

      // 查询操作符列表
      initOperatorList (v) {
        return v === undefined ? this.operatorList : this.operatorList[v]
      },

      // 查询限制条件模板列表
      async initConditionTemplet(ruleType) {
        try {
          const res = await getConditionTemplet({
            ruleType: ruleType
          })
          if(res.resultCode == 1) {
            res.rows.forEach(item => {
              let tempOperateObj = {}
              tempOperateObj[item.conditionKey] = item.operatorList
              Object.assign(this.operatorList, tempOperateObj)
              let aa = {}
              aa[item.conditionKey] = item.conditionName
              Object.assign(this.operatorObj, aa)
            })
            this.conditionTemplet = res.rows
          } else {
            throw new Error(res.message)
          }
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },

      // 加载支持的银行列表
      async supportedBankList(tradeType, bankCode) {
        try {
          const res = await bankList({
            tradeType: tradeType,
            bankCode: bankCode
          })
          if(res.resultCode == 1) {
            this.allBankList = res.data
            this.objList ['BANK_CODE'] =  res.data
          } else {
            throw new Error(res.message)
          }
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },

      // 加载业务编号列表
      async getProductFn(tradeType, bankCode) {
        try {
          const res = await getProduct()
          // let arr = []
          // for( let i in res) {
          //   let obj={}
          //   obj["proNo"] = i
          //   obj["proNa"] = res[i]
          //   arr.push(obj)
          // }
          this.productList = res
          this.objList ['PRODUCT_NO'] =  res
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },
      queryChannelCodeFn () {
        queryChannelCode().then((res) => {
          this.channelCodeList = res
        })
      },
      // 修改选中的规则名称
      changeConditionFn (e, key, v) {
        if (e !== key) {
          v.operator = ''
          v.conditionKey = e
          v.conditionName = this.operatorObj[e]
        }
        v.operatorList = this.initOperatorList(e)
        this.form = JSON.parse(JSON.stringify(this.form))
      },
      getRepayTypeFn () {
        getRepayType().then((res) => {
          if (res.resultCode == 0) {
            this.$message({
              type: 'error',
              message: res.errorDesc
            });
          } else {
            this.repayTypeList = res
            this.objList ['REPAY_TYPE'] =  res
          }
        })
      },
      getCommissionOrgCodeFn () {
        getCommissionOrgCode().then((res) => {
          if (res.resultCode == 0) {
            this.$message({
              type: 'error',
              message: res.errorDesc
            });
          } else {
            this.commissionOrgCodeList = res
            this.objList ['COMMISSION_ORG_CODE'] =  res
          }
        })
      },
      getLenderOrgCodeFn () {
        getLenderOrgCode().then((res) => {
          if (res.resultCode == 0) {
            this.$message({
              type: 'error',
              message: res.errorDesc
            });
          } else {
            this.lenderOrgCodeList = res
            this.objList ['LENDER_ORG_CODE'] =  res
          }
        })
      },
      getEntranceOrgCodeFn () {
        getEntranceOrgCode().then((res) => {
          if (res.resultCode == 0) {
            this.$message({
              type: 'error',
              message: res.errorDesc
            });
          } else {
            this.entranceOrgCodeList = res
            this.objList ['ENTRANCE_ORG_CODE'] =  res
          }
        })
      },

      // 查询支付类型
      getWithholdTypeFn () {
        try {
          getWithholdType().then((res) => {
            if (res.resultCode == 0) {
              this.$message({
                type: 'error',
                message: res.errorDesc
              });
            } else {
              this.withholdTypeList = res
              this.objList ['WITHHOLD_TYPE'] =  res
            }
          })
        } catch(err) {
          console.log('获取数据失败', err)
        }
      },

      paramsFn (e, v) {
        if (typeof(e) === 'string') {
          v.params[0] = e
        } else {
          v.params = e
        }
        this.form = JSON.parse(JSON.stringify(this.form))
      }
    }
  }
</script>
<style lang="less">
  .text-align-left>.el-form-item__label {
    text-align: left;
  }

  .text-align-left>.el-form-item__content {
    margin-left: 0 !important;
    margin-right: 10px;
  }

  .border {
    border: dashed 1px lightgrey;
    padding-top: 10px;
    padding-left: 10px;
    margin-bottom: 30px;
  }

  .margin-20 {
    margin: 22px 0;
  }

  .border-top-dash {
    border-top: 1px dashed lightgrey;
  }

  fieldset {
    border: none;
    border-top: 1px dashed lightgrey;
    padding-left: 10px;
  }

  .margin-left-30 {
    margin-left: 30px;
  }

  .margin-bottom-10 {
    margin-bottom: 10px;
  }
</style>
